package com.putprize.semantic;

import java.util.Properties;

import javax.servlet.Servlet;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import com.putprize.semantic.service.SemanticPosServlet;
import com.putprize.semantic.service.SemanticNerServlet;
import com.putprize.semantic.service.DocumentPosProcessServlet;
import com.putprize.semantic.service.DocumentNerProcessServlet;

import com.putprize.semantic.service.DocumentProcessThrift;
import com.putprize.semantic.service.DocumentProcessThriftImpl;

import org.apache.thrift.TProcessor;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;

public class SemanticTaggerServer {
	
	public static void run(Properties prop){
		
		SemanticPoser pos = new SemanticPoser(prop);
		SemanticNerer ner = new SemanticNerer(prop);
		
		int port = Integer.valueOf(prop.getProperty("SERVER_PORT"));
		
		Server server = new Server(port);
		ServletContextHandler root = new ServletContextHandler(server, "");
		
		Servlet posServlet = new SemanticPosServlet(pos);
		Servlet nerServlet = new SemanticNerServlet(ner);
        Servlet posProcessServlet = new DocumentPosProcessServlet(pos);
        Servlet nerProcessServlet = new DocumentNerProcessServlet(ner);
		
		root.addServlet(new ServletHolder(posServlet), "/pos/*");
		root.addServlet(new ServletHolder(nerServlet), "/ner/*");
        root.addServlet(new ServletHolder(posProcessServlet), "/process_pos/*");
        root.addServlet(new ServletHolder(nerProcessServlet), "/process_ner/*");
		
		try {
			server.start();
		} catch (Exception e){
			e.printStackTrace();
		}
		
	}

    public static void runThriftServer(Properties prop){

        SemanticNerer ner = new SemanticNerer(prop);
        SemanticPoser pos = new SemanticPoser(prop);

        TProcessor tp = new DocumentProcessThrift.Processor<
                DocumentProcessThrift.Iface>(
                new DocumentProcessThriftImpl(ner, pos));

        int port = Integer.valueOf(prop.getProperty("SERVER_PORT"));

        try {
            TServerSocket ss = new TServerSocket(port);
            TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(ss);
            tArgs.processor(tp);
            tArgs.protocolFactory(new TBinaryProtocol.Factory());

            TServer server = new TThreadPoolServer(tArgs);

            server.serve();

        } catch (Exception e){
            e.printStackTrace();
        }


    }

}
